package com.laolei.core.datasource.web;

import java.util.Map;

import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.boot.web.servlet.ServletRegistrationBean;
import org.springframework.cglib.beans.BeanMap;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import com.alibaba.druid.support.http.StatViewServlet;
import com.alibaba.druid.support.http.WebStatFilter;
import com.laolei.core.datasource.config.DruidStatConfig;
import com.laolei.core.utils.MapUtils;

@Configuration
@EnableConfigurationProperties(DruidStatConfig.class)
public class DruidWebMvcConfig {

	@SuppressWarnings("unchecked")
	Map<String, String> druidStatParameters(DruidStatConfig druidStatConfig) {
		return MapUtils.n(BeanMap.create(druidStatConfig)).map((k,v)->String.valueOf(v)).to();
	}

	@Bean
	ServletRegistrationBean servletRegistration(DruidStatConfig druidStatConfig) {
		ServletRegistrationBean filterRegistration = new ServletRegistrationBean(new StatViewServlet());
		filterRegistration.setAsyncSupported(true);
		filterRegistration.setEnabled(true);
		filterRegistration.addUrlMappings("/druid/*");
		filterRegistration.setInitParameters(druidStatParameters(druidStatConfig));
		return filterRegistration;
	}

	@Bean
	FilterRegistrationBean filterRegistration(DruidStatConfig druidStatConfig) {
		FilterRegistrationBean filterRegistration = new FilterRegistrationBean(new WebStatFilter());
		filterRegistration.setAsyncSupported(true);
		filterRegistration.setEnabled(true);
		filterRegistration.addUrlPatterns("/*");
		filterRegistration.setInitParameters(druidStatParameters(druidStatConfig));
		return filterRegistration;
	}
}
